package com.example.blockbreaker;

import android.content.SharedPreferences;
import android.os.CountDownTimer;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class CountDownViewModel extends ViewModel {
    private MutableLiveData<Long> smokeFreeTime = new MutableLiveData<>();
    private MutableLiveData<Double> moneySaved = new MutableLiveData<>();
    private MutableLiveData<Integer> cigarettesAvoided = new MutableLiveData<>();

    private SharedPreferences prefs;
    private long quitTimestamp;
    private int dailyCigarettes;
    private double packPrice;

    public void init(SharedPreferences prefs) {
        this.prefs = prefs;
        quitTimestamp = prefs.getLong("quit_timestamp", System.currentTimeMillis());
        dailyCigarettes = prefs.getInt("daily_cigs", 10);
        packPrice = prefs.getFloat("pack_price", 5.0f);

        startTimer();
    }

    private void startTimer() {
        new CountDownTimer(Long.MAX_VALUE, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long currentTime = System.currentTimeMillis();
                long smokeFreeMillis = currentTime - quitTimestamp;
                smokeFreeTime.setValue(smokeFreeMillis);

                // 计算节省的金钱
                double daysSmokeFree = smokeFreeMillis / (1000.0 * 60 * 60 * 24);
                double money = (dailyCigarettes / 20.0) * packPrice * daysSmokeFree;
                moneySaved.setValue(money);

                // 计算避免的香烟数量
                int cigs = (int)(dailyCigarettes * daysSmokeFree);
                cigarettesAvoided.setValue(cigs);
            }

            @Override
            public void onFinish() {}
        }.start();
    }

    public LiveData<Long> getSmokeFreeTime() {
        return smokeFreeTime;
    }

    public LiveData<Double> getMoneySaved() {
        return moneySaved;
    }

    public LiveData<Integer> getCigarettesAvoided() {
        return cigarettesAvoided;
    }
}